import React, { useRef, useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addItem, updateItem } from '../../../store/index.ts';
import './canvas.css';
import { Watermark } from 'antd';
import { Button, Drawer, Select, Input, Modal } from 'antd';
const Canvas = ({ updateSelectedItemStyle, selectedItemColor, selectedItemBold, selectedItemFontSize }) => {
  const [scale, setScale] = useState(1);
  const svgRef = useRef(null);
  const dispatch = useDispatch();
  const items = useSelector((state) => state.items.items);
  const [isDragging, setIsDragging] = useState(false);
  const [isResizing, setIsResizing] = useState(false);
  const [isRotating, setIsRotating] = useState(false); // 新增旋转状态
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [resizeData, setResizeData] = useState(null);
  const [rotateData, setRotateData] = useState(null); // 新增旋转数据
  const [selectedItemId1, setSelectedItemId1] = useState(null);
  const [showPreview, setShowPreview] = useState(false);
  const contentRef = useRef(null);
  const [showControls, setShowControls] = useState(false);
  const [showWatermark, setShowWatermark] = useState(false);
  const [shareableLink, setShareableLink] = useState('');
  const [open, setOpen] = useState(false);
  const [pl, SetPl] = useState(false)
  const [width, setWidth] = useState(600); // 默认宽度
  const [size, setSize] = useState('600 x 600'); // 默认尺寸
  const [format, setFormat] = useState('png'); // 默认格式
  const [shareLinkModalVisible, setShareLinkModalVisible] = useState(false); // 控制分享链接模态框显示状态
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState('');
  const avatars = [
    '../src/assets/image/hellokity.jpg',
    '../src/assets/images/1.png',
    //...
  ];
  const addComment = () => {
    if (newComment.trim() !== '') {
      const newCommentObj = {
        text: newComment,
        id: Date.now(),
        avatar: avatars[Math.floor(Math.random() * avatars.length)], // 随机分配一个头像
        parentName: null, // 初始时没有回复对象，所以 parentName 为 null
      };
      setComments([...comments, newCommentObj]);
      setNewComment('');
    }
  };

  const editComment = (id, newText) => {
    const updatedComments = comments.map(comment =>
      comment.id === id ? { ...comment, text: newText } : comment
    );
    setComments(updatedComments);
  };

  const deleteComment = (id) => {
    const filteredComments = comments.filter(comment => comment.id !== id);
    setComments(filteredComments);
  };

  const handleReply = (parentId) => {
    const replyText = window.prompt('Enter your reply:');
    if (replyText) {
      const parentComment = comments.find(comment => comment.id === parentId);
      if (parentComment) {
        setComments([
          ...comments,
          {
            text: replyText,
            id: Date.now(),
            avatar: avatars[Math.floor(Math.random() * avatars.length)], // 随机分配一个头像
            parentName: parentComment.text, // 设置回复对象的名字为父评论的文本内容
          },
        ]);
      }
    }
  };
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };

  const plshowDrawer = () => {
    SetPl(true)
  }
  const plonClose = () => {
    SetPl(false)
  }
  const handleInput = () => {
    console.log(contentRef.current.innerText);
  };
  const toggleWatermark = () => {
    setShowWatermark(!showWatermark);
  };
  const handleTextClick = (itemId) => {
    console.log(itemId, 'id')
    setSelectedItemId1(itemId)// 更新选中的项目 ID
  };
  // 画布放大
  const handleZoomIn = () => {
    setScale(scale + 0.1);
  };
// 画布缩小
  const handleZoomOut = () => {
    setScale(Math.max(scale - 0.1, 0.1));
  };

  // 获取仓库的颜色和背景图片
  const bgColor = useSelector((state) => state.color.bgColor);
  const bgImageUrl = useSelector((state) => state.images.selectedImages);
 
  // 监听背景图片和背景颜色的变化
  useEffect(() => {
    const svg = svgRef.current;

    // 创建背景矩形
    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    // 矩形的宽高和背景颜色
    rect.setAttribute('width', '100%');
    rect.setAttribute('height', '100%');
    rect.setAttribute('fill', bgColor);

    // 清空 SVG 内容
    while (svg.firstChild) {
      svg.removeChild(svg.firstChild);
    }
    svg.appendChild(rect);// 将背景矩形添加到 SVG 中

    // 添加背景图片
    if (bgImageUrl.length > 0) {
      const img = document.createElementNS('http://www.w3.org/2000/svg', 'image');
      img.setAttribute('href', bgImageUrl[bgImageUrl.length - 1]);// 选择最后一张图片
      img.setAttribute('x', '0');// 设置 x 轴起始位置
      img.setAttribute('y', '0');// 设置 y 轴起始位置
      img.setAttribute('width', '100%');// 设置图片宽度为 100%
      img.setAttribute('height', '100%');// 设置图片高度为 100%
      img.setAttribute('preserveAspectRatio', 'xMidYMid slice');

      svg.appendChild(img);
    }
  }, [bgColor, bgImageUrl]);


  // 处理拖拽放置事件
  const handleDrop = async(e) => {
    e.preventDefault(); // 阻止默认行为
// 如果是图片
    if (e.dataTransfer.types.includes('image')) {
     const imgUrl = JSON.parse(e.dataTransfer.getData('image'));//获取图片
    console.log('imgUrl', imgUrl);
 // 获取目标元素的边界矩形
    const rect = e.target.getBoundingClientRect();
    // 获取坐标
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    // 将图片添加到 Redux store，设置默认大小
    let newItem = {
      id: Date.now(),
      type: 'image',
      x,
      y,
      imgUrl, // 使用URL
      width: 200, // 默认宽度
      height: 200, // 默认高度
    };

      dispatch(addItem(newItem));
      setSelectedItemInfo(newItem);

    } else if (e.dataTransfer.types.includes('text/plain')) {
      const data = JSON.parse(e.dataTransfer.getData('text/plain'));
      console.log('imgUrl11', data)
      const rect = e.target.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // 添加到 Redux store
      dispatch(addItem({
        id: +new Date,
        x, // 使用当前鼠标坐标
        y, // 使用当前鼠标坐标
        width: 100, // 默认宽度
        height: 30, // 默认高度
        content: data.content, // 直接使用内容
        type: 'text' // 设置类型为文本
      }));
    }
  };
  const [selectedItemInfo, setSelectedItemInfo] = useState(null);
  const percentage = Math.round(scale * 100);
  const handleMouseDown = (e, item) => {
    const svg = svgRef.current;
    const rect = svg.getBoundingClientRect();
    const startX = (e.clientX - rect.left) / scale; // 根据缩放调整
    const startY = (e.clientY - rect.top) / scale; // 根据缩放调整
    setIsDragging(true);
    setDragOffset({ x: startX - item.x, y: startY - item.y });
    setSelectedItemId1(item.id);

    // 更新选中元素的信息
    const itemInfo = {
      id: item.id,
      type: item.type,
      x: item.x,
      y: item.y,
      width: item.width,
      height: item.height,
      content: item.type === 'image' ? item.content : null,
      rotation: item.rotation || 0
    };
    setSelectedItemInfo(itemInfo); // 更新选中元素的信息
  };

  // 图片调整大小
  const handleMouseDownResize = (e, item) => {
    e.stopPropagation();
    if (item.id !== selectedItemId1) {
      return;
    }
    const svg = svgRef.current;
    const rect = svg.getBoundingClientRect();
    const startX = e.clientX - rect.left;
    const startY = e.clientY - rect.top;
    setIsResizing(true);
    setResizeData({
      id: item.id,
      originalWidth: item.width,
      originalHeight: item.height,
      startX,
      startY,
      x: item.x,
      y: item.y,
    });
  };
// 旋转
  const handleMouseDownRotate = (e, item) => { // 旋转控制
    e.stopPropagation();
    if (item.id !== selectedItemId1) {
      return;
    }
    const svg = svgRef.current;
    const rect = svg.getBoundingClientRect();
    const centerX = item.x + item.width / 5;
    const centerY = item.y + item.height / 2;
    const startAngle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
    setIsRotating(true);
    setRotateData({ id: item.id, startAngle, centerX, centerY });
    setSelectedItemId1(item.id);
  };
  const handleMouseMove = (e) => {
    const svg = svgRef.current;
    if (svg) {
      const rect = svg.getBoundingClientRect();
      const x = (e.clientX - rect.left) / scale; // 根据缩放调整
      const y = (e.clientY - rect.top) / scale; // 根据缩放调整
      // console.log(x,y)
      // 拖动元素
      if (isDragging) {
        const updatedItems = items.map(item => {
          if (item.id === selectedItemId1) {
            return { ...item, x: x - dragOffset.x, y: y - dragOffset.y };
          }
          return item;
        });
        dispatch(updateItem(updatedItems.find(item => item.id === selectedItemId1)));
      }

      // 调整大小
      if (isResizing && resizeData) {
        const newWidth = Math.max(x - resizeData.x, 20);
        const newHeight = Math.max(y - resizeData.y, 20);
        // 更新物体的宽度和高度
        const updatedItems = items.map(item => {
          if (item.id === resizeData.id) {
            return { ...item, width: newWidth, height: newHeight };
          }
          return item;
        });
        dispatch(updateItem(updatedItems.find(item => item.id === resizeData.id)));
      }

      // 旋转
      if (isRotating && rotateData) {
        const centerX = rotateData.centerX;
        const centerY = rotateData.centerY;
        // 计算当前角度
        const currentAngle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
        const angleDiff = currentAngle - rotateData.startAngle;
        // 更新物体的旋转角度
        const updatedItems = items.map(item => {
          if (item.id === rotateData.id) {
            return { ...item, rotation: (item.rotation || 0) + angleDiff * (180 / Math.PI) }; // 更新旋转角度
          }
          return item;
        });
        dispatch(updateItem(updatedItems.find(item => item.id === rotateData.id)));
      }
    }
  };
  const handleMouseUp = () => {
    setIsDragging(false);
    setIsResizing(false);
    setIsRotating(false); // 结束旋转
    // setSelectedItemId1(null);
    setResizeData(null);
    setRotateData(null);
  };
  useEffect(() => {
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, isResizing, isRotating]);

  const handleWheel = (e) => {
    e.preventDefault();
    const zoomFactor = 0.1;
    const newScale = e.deltaY < 0 ? scale + zoomFactor : scale - zoomFactor;
    setScale(Math.max(newScale, 0.1));
    items.forEach(item => {
      dispatch(updateItem({ ...item, width: item.width * (newScale / scale), height: item.height * (newScale / scale) }));
    });
  };


  // 预览
  const togglePreview = () => {
    setShowPreview(!showPreview)
  }
  // 下载
  const handleDownload = async () => {
    const svg = svgRef.current;

    if (svg) {
      const svgData = new XMLSerializer().serializeToString(svg);
      const svgBlob = new Blob([svgData], { type: 'image/svg+xml' });
      const svgUrl = URL.createObjectURL(svgBlob);

      // 创建一个临时的<img>元素
      const img = new Image();
      img.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        if (ctx) {
          ctx.drawImage(img, 0, 0);
          const pngDataUrl = canvas.toDataURL('image/png');
          const downloadLink = document.createElement('a');
          downloadLink.href = pngDataUrl;
          downloadLink.download = 'canvas.png';
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);
          URL.revokeObjectURL(pngDataUrl);
        } else {
          console.error('Failed to get canvas context');
        }
      };
      img.onerror = () => {
        console.error('Image failed to load.');
        URL.revokeObjectURL(svgUrl);
      };
      img.src = svgUrl;
    } else {
      console.error('SVG element not found.');
    }
  }
  const handleElementClick = (item) => {
    console.log('Received item1111111111111:', item);
    if (item && item.id) {
      if (selectedItemId1 === item.id) {
        setSelectedItemId1(null);
        setShowControls(false);
      } else {
        setSelectedItemId1(item.id);
        setShowControls(true);
      }
    } else {
      console.error('Item is undefined or has no id property');
    }
  };

  useEffect(() => {
    const svg = svgRef.current;
    if (svg) {
      svg.addEventListener('wheel', handleWheel, { passive: false }); // 添加非被动监听器
    }
    return () => {
      if (svg) {
        svg.removeEventListener('wheel', handleWheel);
      }
    };
  }, [scale, items, dispatch]);
  // 分享功能
  const generateShareableLink = () => {
    const svg = svgRef.current;
    if (svg) {
      const svgData = new XMLSerializer().serializeToString(svg);
      const dataUrl = `data:image/svg+xml;base64,${btoa(svgData)}`; // 使用 data URL 存储 SVG 数据
      setShareableLink(dataUrl);
      setShareLinkModalVisible(true); // 打开分享链接模态框
    } else {
      console.error('SVG element not found.');
    }
  };
  return (
    <div className='svg'>
      {showWatermark && (
        <div className='suiy'>
          <Watermark content="包图">
            <div
              style={{
                height: 500,
              }}
            />
          </Watermark>
        </div>
      )}

      <svg
        ref={svgRef}
        width={500}
        height={600}
        style={{
          backgroundColor: bgColor,
          backgroundImage: bgImageUrl ? `url(${bgImageUrl})` : 'none',
          backgroundSize: 'cover',
          transform: `scale(${scale})`,
          transformOrigin: '0 0',
          marginTop: '60px'
        }}
        onWheel={handleWheel}
        onDrop={handleDrop}
        onDragOver={(e) => e.preventDefault()}
        onMouseDown={(e) => {
          const targetItem = items.find(item => {
            const svgItem = svgRef.current?.querySelector(`[data-id="${item.id}"]`);
            return svgItem && svgItem.contains(e.target);
          });
          if (targetItem) {
            handleMouseDown(e, targetItem);
          } else {
            setSelectedItemInfo(null); // 清空状态
            setSelectedItemId1(null)// 清除选中 id
          }
        }}
       
      >
        {items.map((item) => (
          <g key={item.id} onMouseDown={(e) => handleElementClick(item)}>
            {item.type === 'image' ? (
              <>
                <image
                  x={item.x}
                  y={item.y}
                  width={item.width}
                  height={item.height}
                  href={item.imgUrl}
                  transform={`rotate(${item.rotation || 0} ${item.x + item.width / 2} ${item.y + item.height / 2})`} // 应用旋转
                  onMouseDown={(e) => handleMouseDown(e, item)}
                  data-id={item.id} // 添加 data-id 用于后续操作

                />

                {selectedItemId1 === item.id && ( // 仅在选中项时显示边框和旋转点
                  <>
                    <rect
                      x={item.x - 5}
                      y={item.y - 5}
                      width={item.width + 10}
                      height={item.height + 10}
                      stroke="blue"
                      fill="none"
                      strokeWidth="2"
                    />
                    <circle // 左上角
                      cx={item.x - 5}
                      cy={item.y - 5}
                      r={3}
                      fill="blue"
                      cursor="nwse-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 右上角
                      cx={item.x + item.width + 5}
                      cy={item.y - 5}
                      r={3}
                      fill="blue"
                      cursor="nesw-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 左下角
                      cx={item.x - 5}
                      cy={item.y + item.height + 5}
                      r={3}
                      fill="blue"
                      cursor="nesw-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 右下角
                      cx={item.x + item.width + 5}
                      cy={item.y + item.height + 5}
                      r={3}
                      fill="blue"
                      cursor="nwse-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 旋转控制
                      cx={item.x + item.width + 10}
                      cy={item.y + item.height / 2}
                      r={3}
                      fill="red"
                      cursor="pointer"
                      onMouseDown={(e) => handleMouseDownRotate(e, item)}
                    />

                  </>
                )}

              </>
            ) : (
              <>
                <foreignObject
                  x={item.x}
                  y={item.y}
                  width={item.width} // 动态设置宽度
                  height={item.height} // 动态设置高度
                  data-id={item.id}

                >
                  <div
                    contentEditable
                    onInput={handleInput}
                    suppressContentEditableWarning={true}
                    ref={contentRef}
                    style={{
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      transform: `rotate(${item.rotation || 0}deg)`, // 旋转
                      boxSizing: 'border-box', // 确保padding等不会影响宽高
                      fontSize: item.fontSize || selectedItemFontSize,
                      fontWeight: item.bold || selectedItemBold ? 'bold' : 'normal',
                      color: item.color || selectedItemColor,
                    }}
                    onBlur={(e) => {
                      dispatch(updateItem({ ...item, content: e.target.innerText }));

                    }}
                    onClick={() => handleTextClick(item.id)}
                  >
                    {item.content}
                  </div>
                </foreignObject>

                {selectedItemId1 === item.id && ( // 仅在选中项时显示边框和旋转点
                  <>
                    <rect
                      x={item.x - 5}
                      y={item.y - 5}
                      width={item.width + 10}
                      height={item.height + 10}
                      stroke="blue"
                      fill="none"
                      strokeWidth="2"
                    />
                    <circle // 左上角
                      cx={item.x - 5}
                      cy={item.y - 5}
                      r={3}
                      fill="blue"
                      cursor="nwse-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 右上角
                      cx={item.x + item.width + 5}
                      cy={item.y - 5}
                      r={3}
                      fill="blue"
                      cursor="nesw-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 左下角
                      cx={item.x - 5}
                      cy={item.y + item.height + 5}
                      r={3}
                      fill="blue"
                      cursor="nesw-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 右下角
                      cx={item.x + item.width + 5}
                      cy={item.y + item.height + 5}
                      r={3}
                      fill="blue"
                      cursor="nwse-resize"
                      onMouseDown={(e) => handleMouseDownResize(e, item)}
                    />
                    <circle // 旋转控制
                      cx={item.x + item.width + 10}
                      cy={item.y + item.height / 2}
                      r={5}
                      fill="red"
                      cursor="pointer"
                      onMouseDown={(e) => handleMouseDownRotate(e, item)}
                    />

                  </>
                )}

              </>
            )}
          </g>
        ))}
      </svg>

      <div className='suo'>
        <button onClick={handleZoomIn}>+</button>
        <span style={{ margin: '0 10px' }}>{Math.round(scale * 100)}%</span>
        <button onClick={handleZoomOut}>-</button>
        <button onClick={togglePreview}>预览</button>
        <button onClick={showDrawer}>下载</button>
        <button onClick={generateShareableLink}>生成分享链接</button>
        {/* 分享 */}
        <Modal
          title="分享链接"
          visible={shareLinkModalVisible}
          onCancel={() => setShareLinkModalVisible(false)}
          footer={[
            <Button key="back" onClick={() => setShareLinkModalVisible(false)}>
              关闭
            </Button>,
            <Button key="copy" type="primary" onClick={() => navigator.clipboard.writeText(shareableLink)}>
              复制链接
            </Button>,
          ]}
        >
          <p>您的分享链接：</p>
          <a href={shareableLink} target="_blank" rel="noopener noreferrer">
            {shareableLink}
          </a>
          <p>请将此链接分享给其他人，他们可以在浏览器中打开此链接查看 SVG 画布。</p>
        </Modal>
        {/* 下载 */}
        <Drawer title="下载图片" onClose={onClose} open={open} mask={false}>
          <Button onClick={onClose}>关闭</Button>
          <div style={{ marginBottom: 16 }}>
            <label>选择格式:</label>
            <Select
              defaultValue={format}
              onChange={value => setFormat(value)}
              style={{ width: 120, marginLeft: 8 }}
            >
              <Select.Option value="png">PNG</Select.Option>
              <Select.Option value="jpeg">JPEG</Select.Option>
              <Select.Option value="webp">WEBP</Select.Option>
            </Select>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label>宽度:</label>
            <Input
              type="number"
              value={width}
              onChange={e => setWidth(e.target.value)}
              style={{ width: 120, marginLeft: 8 }}
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <label>尺寸:</label>
            <Input
              type="text"
              value={size}
              onChange={e => setSize(e.target.value)} // 设置尺寸
              placeholder="宽度 x 高度"
              style={{ width: 120, marginLeft: 8 }}
            />
          </div>
          <Button type="primary" onClick={handleDownload}>下载</Button>
        </Drawer>

        <button onClick={toggleWatermark}>水印</button>
        <button onClick={plshowDrawer}>评论</button>
        {/* 评论 */}
        <Drawer title="评论" onClose={plonClose} open={pl} mask={false}>
          <Button onClick={plonClose}>关闭</Button>
          {comments.map(comment => (
            <li key={comment.id}>
              <img src={comment.avatar} alt="Avatar" style={{ width: '30px', height: '30px' }} />
              <span style={{ border: '1px solid #000', width: '200px', height: '50px', display: 'block' }}>{comment.text}</span>
              {comment.parentName && <span>回复 {comment.parentName}</span>}
              <button onClick={() => editComment(comment.id, prompt('Enter new comment text:', comment.text))}>编辑</button>
              <button onClick={() => deleteComment(comment.id)}>删除</button>
              <button onClick={() => handleReply(comment.id)}>回复</button>
            </li>
          ))}
          <div>
            <input
              type="text"
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
            />
            <button onClick={addComment}>评论</button>
            <ul>
              {comments.map(comment => (
                <li key={comment.id}>
                  <img src={comment.avatar} alt="Avatar" style={{ width: '30px', height: '30px' }} />
                  {comment.text}
                  {comment.parentName && <span>回复 {comment.parentName}</span>}
                  <button onClick={() => editComment(comment.id, prompt('Enter new comment text:', comment.text))}>编辑</button>
                  <button onClick={() => deleteComment(comment.id)}>删除</button>
                  <button onClick={() => handleReply(comment.id)}>回复</button>
                </li>
              ))}
            </ul>
          </div>
        </Drawer>
        <button className='cjwt'>？</button>
        {/* <button onClick={generateShareableLink}>生成分享链接</button> */}
      </div>
      {showPreview && (
        <div className='preview'>
          <h2>画布预览</h2>
          <svg
            width={600}
            height={700}
            style={{ backgroundColor: 'white', marginLeft: '100px', textAlign: 'center' }}
            dangerouslySetInnerHTML={{
              __html: svgRef.current?.innerHTML,
            }}
          />
          <button onClick={togglePreview}>关闭预览</button>
        </div>
      )}
    </div>
  );
};

export default Canvas;